package com.wust.database;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.os.Environment;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;

import com.wust.R;
import com.wust.util.ConstDefine;

public class KnowledgeDatabase{

	private Context context;
	public KnowledgeDatabase(Context context)
	{
		this.context=context;
		 boolean dbExist = checkDataBase();
		  if(dbExist){
			  
		  }else{//不存在就把raw里的数据库写入手机
		          try{
		            copyDataBase();
		            }catch(IOException e){
		                     throw new Error("Error copying database");
		                 }
		  }
	}
	 /**

	         * 判断数据库是否存在
	
	         * @return false or true
	
	         */
	        public boolean checkDataBase(){
	            SQLiteDatabase checkDB = null;
	            try{
	            	String databaseFilename = ConstDefine.DatabaseFactoryUtil.DATABASE_PATH+
	            			ConstDefine.DatabaseFactoryUtil.EXIST_DATABASE;
	                checkDB =SQLiteDatabase.openDatabase(databaseFilename, null,
	                        SQLiteDatabase.OPEN_READONLY);
	            }catch(SQLiteException e){
	             
	            }
	            if(checkDB!=null){
	                checkDB.close();
	            }
	            return checkDB !=null?true:false;
	        }
	        /**
	         * 复制数据库到手机指定文件夹下
	         * @throws IOException
	         */
	        public void copyDataBase() throws IOException{
	            String databaseFilenames =ConstDefine.DatabaseFactoryUtil.DATABASE_PATH+
            			ConstDefine.DatabaseFactoryUtil.EXIST_DATABASE;
	            File dir = new File(Environment.getExternalStorageDirectory()+ConstDefine.DatabaseFactoryUtil.DATABASE_PATH);
	            if(!dir.exists())//判断文件夹是否存在，不存在就新建一个
	                dir.mkdir();
	            FileOutputStream os = null;
	            try{
	                os = new FileOutputStream(databaseFilenames);//得到数据库文件的写入流
	            }catch(FileNotFoundException e){
	                e.printStackTrace();
	            }
	            InputStream is = context.getResources().openRawResource(R.raw.daying_knowledge);//得到数据库文件的数据流
	            byte[] buffer = new byte[8192];
	            int count = 0;
	            try{	                 
	            	while((count=is.read(buffer))>0){
	            		os.write(buffer, 0, count);
	                    os.flush();
	                }
	            }catch(IOException e){
	                 
	            }
	            try{
	            	is.close();
	                os.close();
	            }catch(IOException e){
	                e.printStackTrace();
	            }
	        }


}
